package ctrl

import (
	"fmt"
	"log"
	"net/http"

	"gitee.com/cheng470/openai/service"
	"gitee.com/cheng470/openai/util"
)

type Ctrl2 struct {
	fileService  service.FileService
	txAsrService service.TxAsrService
	txTtsService service.TxTtsService
	chatService  service.ChatService
}

func NewController2(fileServcie service.FileService, txAsrService service.TxAsrService,
	txTtxService service.TxTtsService, chatService service.ChatService) *Ctrl2 {
	return &Ctrl2{
		fileService:  fileServcie,
		txAsrService: txAsrService,
		txTtsService: txTtxService,
		chatService:  chatService,
	}
}

// 音频转文本接口
func (c *Ctrl2) Audio2text(w http.ResponseWriter, r *http.Request) {
	r.Body = http.MaxBytesReader(w, r.Body, 3*1024*1024) // 3 Mb
	if err := r.ParseMultipartForm(3 << 20); err != nil {
		log.Println(err)
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte("文件大于3M"))
		return
	}
	file, handler, err := r.FormFile("file")
	if err != nil {
		log.Println(err)
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte("文件解析失败"))
		return
	}
	defer file.Close()

	// 保存到本地磁盘
	err = c.fileService.SaveToLocal(file, handler.Filename)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte("文件保存失败"))
		return
	}

	// 调用腾讯云进行解析
	resp, err := c.txAsrService.HandleSentenceRecognition2(handler.Filename, r.FormValue("fileFormat"))
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte("网络错误"))
		return
	}
	c.OutputJson(w, resp)
}

// 文本转音频接口
func (c *Ctrl2) Text2audio(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	text := r.Form.Get("text")
	if len(text) == 0 {
		log.Println("缺少参数 text")
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte("缺少参数 text"))
		return
	}

	volume := GetParamIntD(r, "volume", 0)
	speed := GetParamIntD(r, "speed", 0)
	voiceType := GetParamIntD(r, "voiceType", 0)
	emotionCategory := GetParamString(r, "emotionCategory")
	emotionIntensity := GetParamIntD(r, "emotionIntensity", 0)

	resp, err := c.txTtsService.HandleText2Audio2(text, volume, speed, voiceType, emotionCategory, emotionIntensity)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte("文件打开失败"))
		return
	}
	c.OutputJson(w, resp)
}

// 聊天接口
func (c *Ctrl2) Chat(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	content := r.Form.Get("content")
	if len(content) == 0 {
		log.Println("缺少参数 content")
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprintln(w, "缺少参数 content")
		return
	}
	resp, err := c.chatService.HandleChat2(content)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte("网络错误"))
		return
	}
	c.OutputJson(w, resp)
}

func (c *Ctrl2) OutputJson(w http.ResponseWriter, resp interface{}) {
	w.Header().Set("Content-Type", "application/json;charset=UTF-8")
	w.Write([]byte(util.JsonEncode(resp)))
}
